package com.test.qpbgboot.base.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.test.qpbgboot.base.config.AlipayConfig;
import com.test.qpbgboot.base.exception.ServiceException;
import com.test.qpbgboot.base.response.ResultStatus;
import com.test.qpbgboot.base.service.PayService;
import com.test.qpbgboot.user.pojo.entity.PersonalAccountLog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
@Slf4j
public class PayServiceImpl implements PayService {

    @Autowired
    private AlipayClient alipayClient;
    @Value("${alipay.notify_url}")
    private String notifyUrl;
    @Value("${alipay.return_url}")
    private String returnUrl;

    @Override
    public String payByAlipay(PersonalAccountLog accountLog, String notifyUrlSuffix
            , String returnUrlSuffix) {
        log.debug("支付宝支付业务，参数:{},{},{}", accountLog, notifyUrlSuffix, returnUrlSuffix);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(notifyUrl);
        request.setReturnUrl(returnUrl);
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", accountLog.getOrderNo());
        bizContent.put("total_amount", accountLog.getAmount());
        bizContent.put("subject", accountLog.getTMessage());
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        request.setBizContent(bizContent.toJSONString());
        try {
            return alipayClient.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void payNotifyByAlipay(Map<String, String> params) {
        log.debug("处理支付宝异步回调业务，参数:{}", params);
        boolean signVerified;
        try {
            signVerified = AlipayConfig.aliSignature(params);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        if (!signVerified) {
            throw new ServiceException(ResultStatus.SIGNATURE_VERIFICATION_FAILED);
        }
        if("TRADE_SUCCESS".equals(params.get("trade_status"))) {
            log.info("======================支付宝异步回调===========");
            log.info("交易名称：{}", params.get("subject"));
            log.info("订单号：{}", params.get("out_trade_no"));
            log.info("支付宝交易号：{}", params.get("trade_no"));
            log.info("交易金额：{}", params.get("total_amount"));
            log.info("交易状态：{}", params.get("trade_status"));
            log.info("支付时间：{}", params.get("gmt_payment"));
            log.info("买家实付金额：{}", params.get("buyer_pay_amount"));
            log.info("买家在支付宝唯一id: {}", params.get("buyer_id"));
        }
    }
}
